import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';
import {saveAs} from "file-saver";
import JSZip from "jszip";

const downloadPDF = (
    el: HTMLElement,
    pdfName: string,
    callback?: Function
): void => {
    html2canvas(el, {
        scale: 2, // 设置缩放
        useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。,
        logging: false // 打印日志用的 可以不加默认为false
    }).then((canvas) => {
        // el.setAttribute("crossOrigin",'anonymous');
        const contentWidth = canvas.width;
        const contentHeight = canvas.height;
        //一页pdf显示html页面生成的canvas高度;
        const pageHeight = (contentWidth / 592.28) * 841.89;
        //未生成pdf的html页面高度
        let leftHeight = contentHeight;
        //页面偏移
        let position = 0;
        //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
        const imgWidth = 595.28;
        const imgHeight = (595.28 / contentWidth) * contentHeight;
        const pageData = canvas.toDataURL('image/jpeg', 1.0);
        const pdf = new JsPDF('', 'pt', 'a4');

        if (leftHeight < pageHeight) {
            //在pdf.addImage(pageData, 'JPEG', 左，上，宽度，高度)设置在pdf中显示；
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
        } else {
            // 分页
            while (leftHeight > 0) {
                pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
                leftHeight -= pageHeight;
                position -= 841.89;
                //避免添加空白页
                if (leftHeight > 0) {
                    pdf.addPage();
                }
            }
        }
        pdf.save(pdfName);
        if (callback) callback();
    });
};

const downloadPNG = async (
    el: HTMLElement,
    pngName: string,
    single: boolean = true,
    callback?: Function
) => {
    html2canvas(el, {
        scale: 2, // 设置缩放
        useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。,
        logging: false // 打印日志用的 可以不加默认为false
    }).then((canvas) => {
        canvas.toBlob((blob) => {
            if (!blob) return;
            if (single) saveAs(blob, pngName)
            else{
               cropBlobImageToShortImages(blob, 2320).then(blobs =>{
                   downloadZip(blobs, pngName)
               })
            }
        }, 'image/png')

        if (callback) {
            callback()
        }
    });

}

const downloadZip = (blobs: Blob[], pngName:string) => {
    const zip = new JSZip();
    blobs.forEach((blob, index) =>{
        zip.file(`${pngName}_${index}.png`, blob)
    })
    zip.generateAsync({type: 'blob'}).then(content =>{
        saveAs(content, pngName)
    })
}

const cropBlobImageToShortImages = (blob: Blob, shortHeight: number): Promise<Blob[]> => {
    return new Promise((resolve, reject) => {
        const img = new Image();
        const objectURL = URL.createObjectURL(blob); // 将Blob转换为Object URL
        img.src = objectURL;

        img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            if (!ctx) {
                URL.revokeObjectURL(objectURL); // 释放Object URL
                reject(new Error('无法获取Canvas上下文'));
                return;
            }

            const originalWidth = img.width;
            const originalHeight = img.height;
            canvas.width = originalWidth; // 设置Canvas宽度与原图一致
            canvas.height = shortHeight; // 设置Canvas高度为短图的高度

            const numShortImages = Math.ceil(originalHeight / shortHeight); // 计算需要裁剪的短图数量
            const blobs: Blob[] = [];

            for (let i = 0; i < numShortImages; i++) {
                const startY = i * shortHeight; // 当前短图的起始Y坐标
                const currentHeight = Math.min(shortHeight, originalHeight - startY); // 当前短图的实际高度
                ctx.clearRect(0,0, canvas.width, canvas.height);
                ctx.fillStyle = 'white'
                ctx.fillRect(0, 0, canvas.width, canvas.height); // 填充整个Canvas为白色
                // 裁剪图片并绘制到Canvas上
                ctx.drawImage(img, 0, startY, originalWidth, currentHeight, 0, 0, originalWidth, currentHeight);

                // 将Canvas内容导出为Blob
                canvas.toBlob((blob) => {
                    if (blob) {
                        blobs.push(blob);
                    }

                    // 如果所有短图都已生成，则返回结果
                    if (blobs.length === numShortImages) {
                        URL.revokeObjectURL(objectURL); // 释放Object URL
                        resolve(blobs);
                    }
                }, 'image/jpeg', 0.95); // 导出为JPEG格式，质量为95%
            }
        };

        img.onerror = (error) => {
            URL.revokeObjectURL(objectURL); // 释放Object URL
            reject(new Error(`图片加载失败: ${error}`));
        };
    });
};


export {downloadPDF, downloadPNG}
